// page/pageone/index.js
var config = require('../../config.js');
var loadRequest = require('loadRequest.js');

var app = getApp();
var page = 0;
var size = 6;
var tab_index = 0;//索引 最新，最热，推荐
var tab_hot = {};//存放最热信息 包含分页page，pageSize
var tab_new = {};//存在最新信息 包含分页page，pageSize
var tab_tj = {};//存在推荐信息  包含分页page，pageSize
var name = '';//登陆用户

var top_list = [];
var top = {};

var touchDot = 0;//触摸时的原点
var time = 0;//  时间记录，用于滑动时且时间小于1s则执行左右滑动
var interval = "";// 记录/清理 时间记录
var tmpFlag = true;// 判断左右华东超出菜单最大值时不再执行滑动事件
var favorList=[];//此方法是点击收藏的时候记录的收藏信息
Page({
  data: {
    indicatorColor: "rgba(144, 202, 249, .8)",
    indicatorActiveColor: "#2979ff",
    indicatorDots: true,
    autoplay: true,
    //vertical:true,
    interval: 5000,
    duration: 1000,
    animationData: {},
    id: null,
    userinfo: null,
    title: '',
    tip: config.barTitle,
    day:'',
    clickfobj:'',//点击对象
    list: [],//当前页展示的列表数据
    tab_list: [],
    username: '',
    make_display: 'none',
    showTime:'',
    lastLoadTime: new Date().getTime(),
    //tab_menu:{}//菜单，中存在tab_list,class_name
    footerConfig: {
      Index: true
    },
    windowHeight:0,
    windowWidth:0,
    tab_index_index:0,
    coverUrl:'',
    clickId: 0,//判断重复点击
    favorlist:[],
    //所有图片的高度  
    //imgheights: [],
    //图片宽度  
    //imgwidth: 750,
    headList: []//首页最初的两个值
  },
  //imageLoad: function (e) {
    //获取图片真实宽度  
   // var imgwidth = e.detail.width,
      //imgheight = e.detail.height,
      //宽高比  
     // ratio = imgwidth / imgheight;
    //console.log(imgwidth, imgheight)
    //计算的高度值  
    //var viewHeight = 750 / ratio;
   // var imgheight = viewHeight
   // var imgheights = this.data.imgheights
    //把每一张图片的高度记录到数组里  
    //imgheights.push(imgheight)
    //this.setData({
      //imgheights: imgheights,
   // })
  //},
  bindchange: function (e) {
    console.log(e.detail.current)
    this.setData({ current: e.detail.current })
  } ,
  changeIndicatorDots: function (e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function (e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function (e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function (e) {
    this.setData({
      duration: e.detail.value
    })
  },
  upper: function (e) {
    console.log(e)
  },
  lower: function (e) {
    console.log(e)
  },
  scroll: function (e) {
    console.log(e)
  },
  scrollToTop: function (e) {
    this.setAction({
      scrollTop: 0
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.getUserName(function (user_name) {});
    wx.showLoading({
      title: '加载中···',
    });

    tab_hot = {};//存放最热信息 包含分页page，pageSize
    tab_new = {};//存在最新信息 包含分页page，pageSize
    tab_tj = {};//存在推荐信息  包含分页page，pageSize

    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          windowHeight: res.windowHeight*0.6,
          windowWidth: res.windowWidth
        })
      }
    })
    var that = this;
    top_list = [];

    //表示最新，最热，推荐处的数组

    top.name = '最新';
    top.class_name = 'active';
    top_list.push(top);

    top = {};
    top.name = '最热';
    top.class_name = '';
    top_list.push(top);

    top = {};
    top.name = '推荐';
    top.class_name = '';
    top_list.push(top);

    that.setData({
      tab_list: top_list
    });
    var data = {
      tagName: app.globalData.tagName,
      type: 'VIDEO',
      page: page,
      size: size,
      //sort: 'showTime,desc',
      sort: 'S',
    }
    loadRequest.getTwoSeries(that);
    //加载首条数据
    loadRequest.load_list(data, page, tab_new, that);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: () => {
    wx.setNavigationBarTitle({
      title: config.barTitle
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })

    this.animation = animation
    animation.rotate(180).step()
    animation.rotate(0).step()

    this.setData({
      animationData: animation.export()
    })

    setTimeout(function () {
      animation.translate(45).step()
      animation.translate(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 1000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  pullUpLoad: function (e) {
  },
  pullDownRefresh: function () {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: config.shareDes,
      path: '/pages/index/index',
      imageUrl: '../images/sharepic_1.jpg'
    }
  },
  refesh: function () {
  },
  loadMore: function () {
    var that = this;
    var curTime = new Date().getTime();
    //上一次加载的时间
    var lastTime = this.data.lastLoadTime;
    that.setData({
      lastLoadTime: curTime
    });
    if (curTime - lastTime < 300) {
      return;
    }
    if (tab_index == 0) {
      var currentPage = tab_new.page+1 ;
      if (currentPage <= tab_new.pageSize - 1) {//当前页小于总页数，那就请求数据并存放在list中 下一页
        wx.showLoading({
          title: '加载中···',
        });
        tab_new.page = currentPage;
        var data = {
          tagName: app.globalData.tagName,
          page: currentPage,
          size: size,
          //sort: 'showTime,desc',
          sort: 'S',
          type: 'VIDEO'
        }
        loadRequest.loadPage(data, tab_new, that);
      }else{
        wx.showLoading({
          title: '没有更多了...',
        });
        setTimeout(function(){
          wx.hideLoading();
        }, 1000);
      }
    } else if (tab_index == 1) {//最热
      var currentPage = tab_hot.page+1 ;
      if (currentPage <= tab_hot.pageSize - 1) { //当前页小于总页数，那就请求数据并存放在list中 下一页
        wx.showLoading({
          title: '加载中···',
        });
        tab_hot.page = currentPage;
        var data = {
          tagName: app.globalData.tagName,
          page: currentPage,
          size: size,
          //sort: 'counter.viewingCount,desc',
          sort: 'V',
          type: 'VIDEO',
        };
        loadRequest.loadPage(data, tab_hot, that);
       
      }else{
        wx.showLoading({
          title: '没有更多了...',
        });
        setTimeout(function () {
          wx.hideLoading();
        }, 1000);
      }
    } else {//推荐
      var currentPage = tab_tj.page+1 ;
      if (currentPage < tab_tj.pageSize - 1) {//当前页小于总页数，那就请求数据并存放在list中 下一页
       
        wx.showLoading({
          title: '加载中···',
        });
        tab_tj.page = currentPage;
        var data = {
          tagName: app.globalData.tagName,
          page: currentPage,
          size: size,
          sort: 'showTime,desc',
          type: 'VIDEO',
          status: 'QUALIFIED'
        };
        loadRequest.load_status_page(data, tab_tj, that);
        
      }else{
        wx.showLoading({
          title: '没有更多了...',
        });
        setTimeout(function () {
          wx.hideLoading();
        }, 1000);
      }
    }
   
  },

  /**
   * 进入播放页面
   */
  inplay: function (e) {
    var id = e.currentTarget.dataset.id;
    var title = e.currentTarget.dataset.title;
    if(id==0||id==null){ return;}
    if (this.data.clickId==id){return;}
    this.setData({ clickId:id});
    var url = '../video/video?id=' + e.currentTarget.dataset.id+'&title='+title;
    wx.navigateTo({url: url})
  },
  inplay_series: function (e) {
    var id = e.currentTarget.dataset.id;
    if (id == 0 || id == null) {
      return;
    }
    if (this.data.clickSeriesId == id) {
      return;
    }
    this.setData({
      clickSeriesId: id
    });
    wx.navigateTo({
      url: '../search/seriesList/serieslist?id=' + id,
    });
  },
  bind_load: function (e) {
    var that = this;
    var data_index = e.currentTarget.dataset.id;
    this.slip(data_index);

  }, favor: function (e) {//收藏或取消
    var that = this;
    var idd = e.currentTarget.dataset.id;
    var fid = e.currentTarget.dataset.fid;//是否收藏1 是，0 否
    if(idd==0||idd==null){return;}
  

    var clickfobj=this.data.clickfobj;
    if (clickfobj && clickfobj.id == idd && clickfobj.fid==fid){
      return;
    }else{
      var clickfobj = { id: idd, fid: fid };
      this.setData({
        clickfobj: clickfobj
      });
    }
    if (fid == '1') {//表示取消收藏   
     app.getNUserName(function(username){
       if(username){
         loadRequest.add_rem_favorite(idd, username, 'remove',
           loadRequest.render_page(idd, '0', tab_index, tab_new, tab_hot, tab_tj, that)
         );
       }
     });
    } else {//表示需要收藏
      app.getNUserName(function (username) {
        if(username){
          loadRequest.add_rem_favorite(idd, username, 'add',
            loadRequest.render_page(idd, '1', tab_index, tab_new, tab_hot, tab_tj, that)
          );
        }
      });
    }
  },
  play: function (e) {
  }, search: function (e) {
    // wx.reLaunch({
    //   url: '../waterfall/waterfall',
    // })
    wx.switchTab({
      url: '../waterfall/waterfall',
    });
  }, user: function (e) {
    // wx.reLaunch({
    //   url: '../user/user',
    // })
    wx.switchTab({
      url: '../user/user',
    });
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
    startX = that.data.startX,//开始X坐标
    startY = that.data.startY,//开始Y坐标
    touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
    touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
    //获取滑动角度
    angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    //滑动超过30度角 return
    if (Math.abs(angle) > 30) return;
    var curIndex = tab_index;
    if (touchMoveX > startX && tmpFlag) {//右滑
      tab_index = tab_index == 0 ? 0 : tab_index - 1;
      if (curIndex==tab_index){
          return;
      }
      tmpFlag = false;
      this.slip(tab_index);
    } 
    else if (touchMoveX < startX && tmpFlag){//左滑
      tab_index = tab_index == 2 ? 2 : tab_index + 1;
      if (curIndex == tab_index) {
        return;
      }
      tmpFlag=false;
      this.slip(tab_index);
    } 

  }, /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  }, touchend:function(e){
    tmpFlag = true;
  },
  slip: function (data_index){
    var that = this;
    tab_index = data_index;
    //样式改变
    for (var i = 0; i < top_list.length; i++) {
      if (tab_index == i) {
        top_list[i].class_name = 'active';
      } else {
        top_list[i].class_name = '';
      }
    }
    that.setData({
      tab_list: top_list,
      tab_index_index: tab_index,
      hasRefesh: false
    });
    var list_list = [];
   // var favorlist=[];
    that.setData({
      list: list_list,
     // favorlist: favorlist
    });
    if (tab_index == 1) {
      if (undefined == tab_hot.list) {
        var data = {
          tagName: app.globalData.tagName,
          page: page,
          size: size,
          //sort: 'counter.viewingCount,desc',
          sort: 'V',
          type: 'VIDEO'
        };
        loadRequest.load_hot_list(data, 0, tab_hot, that);
        
      }
        list_list = tab_hot.list;
        //favorlist = tab_hot.favorlist;
    } else if (tab_index == 2) {
      if (undefined == tab_tj.list) {
        var data = {
          tagName: app.globalData.tagName,
          page: page,
          size: size,
          sort: 'showTime,desc',
          type: 'VIDEO',
          status: 'QUALIFIED'
        };
        loadRequest.load_status_list(data, 0, tab_tj, that);
        
      }
        list_list = tab_tj.list; 
       // favorlist = tab_tj.favorlist;
    } else {
      if (undefined == tab_new.list) {
        var data = {
          tagName: app.globalData.tagName,
          type: 'VIDEO',
          page: page,
          size: size,
         // sort: 'showTime,desc',
          sort: 'S',
        }
        loadRequest.load_list(data, page, tab_new, that);
      }
        list_list = tab_new.list;
        //favorlist = tab_new.favorlist;
    }
    that.setData({
      list: list_list,
      //favorlist: favorlist
    });
   
  }

})
